package com.situ.user.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.situ.user.bean.Goods;
import com.situ.user.bean.Order;
import com.situ.user.bean.OrderDetails;
import com.situ.user.bean.Shopcart;
import com.situ.user.bean.User;
import com.situ.user.mapper.GoodsMapper;
import com.situ.user.mapper.OrderDetailsMapper;
import com.situ.user.mapper.OrderMapper;
import com.situ.user.mapper.ShopcartMapper;
import com.situ.user.mapper.UserMapper;
import com.situ.user.service.OrderService;
import com.situ.user.utils.MD5Util;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private ShopcartMapper cartMapper;

	@Autowired
	private OrderDetailsMapper orderDetailsMapper;

	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private UserMapper userMapper;

	@Override
	@Transactional
	public Order add(Integer userId, Integer[] cartId) throws Exception {
		// 1.判断cartId长度
		if (cartId == null || cartId.length == 0) {
			throw new Exception("订单中不包含任何商品的！！！！ 生成个p");
		}
		List<Shopcart> carts = new ArrayList<>();
		// 2.查询购物车的信息
		for (int i = 0; i < cartId.length; i++) {
			Shopcart cart = cartMapper.selectByPrimaryKey(cartId[i]);
			carts.add(cart);
			// 2.1验证cart是否存在
			if (cart == null) {
				throw new Exception("购物车的信息查询失败！！订单生成失败");
			}
			// 2.2验证cart是不是自己的
			if (userId != cart.getUserId()) {
				throw new Exception("购物车的用户信息出错！！订单生成失败");
			}
			// 3.3验证商品库存是否够用
			if (cart.getCount() > cart.getGoods().getCount()) {
				throw new Exception("购买的商品库存不足！！订单生成失败");
			}
			// 3.4购买的数量不能是0
			if (cart.getCount() <= 0) {
				throw new Exception("购买的商品数量不能小于1！！订单生成失败");
			}
		}
		// 3.保存订单
		Order order = new Order();
		// UUID
		order.setId(UUID.randomUUID().toString());
		order.setUserId(userId);
		// 保存到数据库
		int insert = orderMapper.insert(order);
		if (insert <= 0) {
			throw new Exception("订单保存失败");
		}
		// 4.遍历cart中对策数据，生成订单详情
		for (int i = 0; i < carts.size(); i++) {
			OrderDetails orderDetails = new OrderDetails();
			orderDetails.setOrderId(order.getId());
			orderDetails.setGoodsId(carts.get(i).getGoodsId());
			orderDetails.setCount(carts.get(i).getCount());
			orderDetails.setPrice(carts.get(i).getGoods().getPrice());

			// 保存到数据库
			int insert2 = orderDetailsMapper.insert(orderDetails);
			if (insert2 <= 0) {
				throw new Exception("订单详情保存失败");
			}

		}

		// 5.清理购物车里的信息
		for (int i = 0; i < carts.size(); i++) {
			int key = cartMapper.deleteByPrimaryKey(carts.get(i).getId());
			if (key <= 0) {
				throw new Exception("购物车信息清理失败");
			}
			// 6.扣除商品的库存
			Goods goods = carts.get(i).getGoods();
			goods.setCount(goods.getCount() - carts.get(i).getCount());
			// 写回数据库
			int primaryKey = goodsMapper.updateByPrimaryKey(goods);
			if (primaryKey <= 0) {
				throw new Exception("商品库存扣除失败");
			}
		}

		// 7.查询全部的订单信息 返回
		return orderMapper.selectByPrimaryKey(order.getId());
	}

	@Override
	public Order getById(String orderId) {
		return orderMapper.selectByPrimaryKey(orderId);
	}

	@Override
	public int update(Order order) {
		return orderMapper.updateByPrimaryKey(order);
	}

	@Override
	@Transactional()
	public int pay(String orderId, String paypwd, Integer userId) throws Exception {
		// 1.验证支付密码
		User user = userMapper.selectByPrimaryKey(userId);
		if (user.getPaypwd() == null) {
			// 未设置支付密码
			throw new Exception("未设置支付密码");

		}
		if (!user.getPaypwd().equals(MD5Util.getMD5(paypwd))) {
			// 密码不对
			throw new Exception("密码不对");
		}
		// 2. 扣款
		Order order = orderMapper.selectByPrimaryKey(orderId);
		BigDecimal sum = new BigDecimal(0);
		for (int i = 0; i < order.getOrderDetails().size(); i++) {
			OrderDetails orderDetails = order.getOrderDetails().get(i);
			BigDecimal total = orderDetails.getPrice().multiply(new BigDecimal(orderDetails.getCount()));
			sum = sum.add(total);
		}
		if (user.getMoney().compareTo(sum) < 0) {
			// 余额不足
			throw new Exception("账户余额不足");
		}
		// 扣除相应的钱
		user.setMoney(user.getMoney().subtract(sum));
		// 更新余额
		int update = userMapper.updateByPrimaryKey(user);
		if (update <= 0) {
			// 扣款失败
			throw new Exception("扣款失败");
		}
		// 3. 修改订单状态
		if (order.getStatus() != 0) {
			// 订单不是未支付的订单
			throw new Exception("订单状态错误！无法完成支付");
		}
		order.setStatus(1); // 已支付
		int i = orderMapper.updateByPrimaryKey(order);
		if (i <= 0) {
			// 订单状态修改失败
			throw new Exception("订单状态修改失败！！无法完成支付");
		}
		return 1;
	}

	@Override
	public List getByUserId(Integer userId) {

		return orderMapper.selectByUserId(userId);
	}

	@Override
	@Transactional
	public int clean() {
		// 清理无效的是订单
		// 查询无效订单
		// 时间在半小时之前 订单的状态（status=0）是未支付
		List<Order> orders = orderMapper.selectInvalid();

		// 清理过期订单
		for (Order order : orders) {
			for (OrderDetails detail : order.getOrderDetails()) {
				// 库存复原
				Goods goods = detail.getGoods();
				goods.setColor(goods.getColor() + detail.getCount());
				goodsMapper.updateByPrimaryKey(goods);
				// 删除订单的详情
				orderDetailsMapper.deleteByPrimaryKey(detail.getId());
			}
			// 删除订单
			orderMapper.deleteByPrimaryKey(order.getId());
		}

		return 1;
	}

}
